package com.dongdong.bookstore.common.api;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;


/**
 * @author chiangkai
 * @date 2021-10-13
 * @email chiangkk@163.com
 */
@RestControllerAdvice(basePackages = "com.dongdong.bookstore")
public class ReturnAdvice implements ResponseBodyAdvice<Object> {
    @Override
    public boolean supports(MethodParameter returnType, Class converterType) {
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        if (body instanceof ResultData) {
            return body;
        }
        if (body instanceof String) {
            response.getHeaders().setContentType(MediaType.parseMediaType(MediaType.APPLICATION_JSON_VALUE));
            try {
                return   new ObjectMapper().writeValueAsString(ResultData.ok((String) body));
            } catch (JsonProcessingException e) {
                e.printStackTrace();
            }
        }
        if (body instanceof Boolean) {
            if ((boolean) body) {
                return ResultData.ok("操作成功");
            }
            return ResultData.fail("操作失败");
        }
        return ResultData.success(body);
    }
    
}
